/**
 * cavion（曹仁道）
 * caorendao187@163.com
 * 2017年6月22日 下午10:09:43
 */
package org.rk.core.common.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * @author cavion @类描述： 2017年6月22日
 */
public class RKHttpUtil {
	public static CloseableHttpClient createSSLClientDefault() {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				// 信任所有
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
			return HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyStoreException e) {
			e.printStackTrace();
		}
		return HttpClients.createDefault();
	}
	public static JSONObject httpGet(String hostName,String url) {
		// 创建HttpClientBuilder
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		// HttpClient
		CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
		HttpGet httpGet = new HttpGet("http://"+hostName+url);
		System.out.println(httpGet.getRequestLine());
		try {
			// 执行get请求
			HttpResponse httpResponse = closeableHttpClient.execute(httpGet);
			// 获取响应消息实体
			HttpEntity entity = httpResponse.getEntity();
			// 响应状态
			System.out.println("status:" + httpResponse.getStatusLine());
			// 判断响应实体是否为空
			if (entity != null) {
				System.out.println("contentEncoding:" + entity.getContentEncoding());
				String resp=EntityUtils.toString(entity);
				System.out.println("response content:" + resp);
				JSONObject result=JSONObject.parseObject(resp);
				return result; 
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭流并释放资源
				closeableHttpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	public static JSONObject httpPost(String hostName,String url,Map<String,String> params) throws UnsupportedEncodingException {
		// 创建HttpClientBuilder
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		// HttpClient
		CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
		StringBuilder reqUrl=new StringBuilder();
		reqUrl.append("http://");
		reqUrl.append(hostName);
		reqUrl.append(url);
		String paramsUrl=RKSocketUtil.genParams(params);
		if(RkStrUtil.hasText(paramsUrl)){
			reqUrl.append("?"+paramsUrl);	
		}
		HttpPost httpPost = new HttpPost(reqUrl.toString());
		System.out.println(httpPost.getRequestLine());
		try {
			// 执行get请求
			HttpResponse httpResponse = closeableHttpClient.execute(httpPost);
			// 获取响应消息实体
			HttpEntity entity = httpResponse.getEntity();
			// 响应状态
			System.out.println("status:" + httpResponse.getStatusLine());
			// 判断响应实体是否为空
			if (entity != null) {
				System.out.println("contentEncoding:" + entity.getContentEncoding());
				String resp=EntityUtils.toString(entity);
				System.out.println("response content:" + resp);
				JSONObject result=JSONObject.parseObject(resp);
				return result; 
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭流并释放资源
				closeableHttpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public static JSONObject httpsGet(String hostName,String url) {
		// HttpClient
		CloseableHttpClient closeableHttpClient = createSSLClientDefault();
		HttpGet httpGet = new HttpGet("https://"+hostName+url);
		System.out.println(httpGet.getRequestLine());
		try {
			// 执行get请求
			HttpResponse httpResponse = closeableHttpClient.execute(httpGet);
			// 获取响应消息实体
			HttpEntity entity = httpResponse.getEntity();
			// 响应状态
			System.out.println("status:" + httpResponse.getStatusLine());
			// 判断响应实体是否为空
			if (entity != null) {
				System.out.println("contentEncoding:" + entity.getContentEncoding());
				String resp=EntityUtils.toString(entity);
				System.out.println("response content:" + resp);
				JSONObject result=JSONObject.parseObject(resp);
				return result; 
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭流并释放资源
				closeableHttpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	public static JSONObject httpsPost(String hostName,String url,Map<String,String> params) throws UnsupportedEncodingException {
		// HttpClient
		CloseableHttpClient closeableHttpClient = createSSLClientDefault();
		StringBuilder reqUrl=new StringBuilder();
		reqUrl.append("https://");
		reqUrl.append(hostName);
		reqUrl.append(url);
		String paramsUrl=RKSocketUtil.genParams(params);
		if(RkStrUtil.hasText(paramsUrl)){
			reqUrl.append("?"+paramsUrl);	
		}
		HttpPost httpPost = new HttpPost(reqUrl.toString());
		System.out.println(httpPost.getRequestLine());
		try {
			// 执行get请求
			HttpResponse httpResponse = closeableHttpClient.execute(httpPost);
			// 获取响应消息实体
			HttpEntity entity = httpResponse.getEntity();
			// 响应状态
			System.out.println("status:" + httpResponse.getStatusLine());
			// 判断响应实体是否为空
			if (entity != null) {
				System.out.println("contentEncoding:" + entity.getContentEncoding());
				String resp=EntityUtils.toString(entity);
				System.out.println("response content:" + resp);
				JSONObject result=JSONObject.parseObject(resp);
				return result; 
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭流并释放资源
				closeableHttpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static void main(String[] args) {
		try {
			/*Map<String,String> params=new HashMap<String,String>();
			params.put("appid", "wxb05da5b418dab547");
			params.put("secret", "05629c6285429ceab4b7de72e0494efa");
			params.put("js_code", "003V5SZd1dTInv0tMVZd1l6JZd1V5SZh");
			params.put("grant_type", "authorization_code");
			RKHttpUtil.httpsPost("api.weixin.qq.com", "/sns/jscode2session",new HashMap<String, String>());*/
			Map<String,String> params=new HashMap<String,String>();
			params.put("code", "003V5SZd1dTInv0tMVZd1l6JZd1V5SZh");
			params.put("username", "沸水");
			RKHttpUtil.httpsPost("www.utqld.com", "/rk/web/third/wx/userMangager/wxUserLogin", params);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
